package com.ddpt.permission.util;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.captcha.generator.RandomGenerator;
import com.lh.center.common.constant.RedisPrefix;
import com.lh.center.common.exception.CommonException;
import com.lh.center.common.exception.ErrorEnum;
import com.lh.center.common.util.MybatisPlusGenerator;
import com.lh.center.permission.api.bo.ImgCodeBean;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class ImageCodeUtil {
    
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 获取图片验证码
     */
    public ImgCodeBean getImgCode() {
        LineCaptcha captcha = CaptchaUtil.createLineCaptcha(60,30,4,0);
        captcha.setGenerator(new RandomGenerator("0123456789",4));
        captcha.createCode();
        String code = captcha.getCode();
        String imageBase64 = captcha.getImageBase64();
        String key = UUID.randomUUID().toString();
        log.info("验证码：codeId：{}，code：{}",key,code);
        System.out.println("codeId：" + key + "，code：" + code);
        ImgCodeBean imgCodeBean = new ImgCodeBean();
        imgCodeBean.setCodeId(key);
        imgCodeBean.setImgCodeBase64(imageBase64);
        stringRedisTemplate.opsForValue().set(RedisPrefix.IMAGE_CODE + key,code,180, TimeUnit.SECONDS);
        return imgCodeBean;
    }

    /**
     * 验证图形验证码
     * @param codeId
     * @param code
     */
    public void verifyCode(String codeId,String code) {
        if(StringUtils.isAnyBlank(codeId,code)) {
            throw new CommonException(ErrorEnum.CRITICAL_PARAM_DEFICIENCY);
        }
        String realCode = stringRedisTemplate.opsForValue().get(RedisPrefix.IMAGE_CODE + codeId);
        if(StringUtils.isBlank(realCode)) {
            throw new CommonException(ErrorEnum.IMAGE_CODE_PAST);
        } else if(!realCode.equalsIgnoreCase(code)) {
            throw new CommonException(ErrorEnum.IMAGE_CODE_INPUT_FAIL);
        }
        stringRedisTemplate.delete(RedisPrefix.IMAGE_CODE + codeId);
    }

    public static void main(String[] args) {
        MybatisPlusGenerator.generator("czy",new String[]{"service_version"},"backstage");
    }
}
